/** @file
  PCI host bridge library instance for Phytium SOC.

  Copyright (C) 2023, Phytium Technology Co., Ltd. All rights reserved.<BR>

  SPDX-License-Identifier: BSD-2-Clause-Patent

**/
#include <Library/DebugLib.h>
#include <Library/DevicePathLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/PciHostBridgeLib.h>
#include <Library/PssiLib.h>

#include <Protocol/PciHostBridgeResourceAllocation.h>
#include <Protocol/PciRootBridgeIo.h>

#include <Pcie.h>

#pragma pack(1)

typedef struct {
  ACPI_HID_DEVICE_PATH     AcpiDevicePath;
  EFI_DEVICE_PATH_PROTOCOL EndDevicePath;
} EFI_PCI_ROOT_BRIDGE_DEVICE_PATH;

#pragma pack ()

#define END_DEVICE_PATH_DEF { END_DEVICE_PATH_TYPE, \
                              END_ENTIRE_DEVICE_PATH_SUBTYPE, \
                              { END_DEVICE_PATH_LENGTH, 0 } \
                            }

#define ACPI_DEVICE_PATH_DEF(UID) {{ ACPI_DEVICE_PATH, ACPI_DP, \
                                     { (UINT8) (sizeof (ACPI_HID_DEVICE_PATH)), \
                                       (UINT8) (sizeof (ACPI_HID_DEVICE_PATH) >> 8)} \
                                     }, \
                                     EISA_PNP_ID (0x0A03), UID \
                                  }

STATIC CONST EFI_PCI_ROOT_BRIDGE_DEVICE_PATH mEfiPciRootBridgeDevicePath[] = {
  //Host Bridge 0
  {
    ACPI_DEVICE_PATH_DEF(0),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 1
  {
    ACPI_DEVICE_PATH_DEF(1),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 2
  {
    ACPI_DEVICE_PATH_DEF(2),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 3
  {
    ACPI_DEVICE_PATH_DEF(3),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 4
  {
    ACPI_DEVICE_PATH_DEF(4),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 5
  {
    ACPI_DEVICE_PATH_DEF(5),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 6
  {
    ACPI_DEVICE_PATH_DEF(6),
    END_DEVICE_PATH_DEF
  },

  //Host Bridge 7
  {
    ACPI_DEVICE_PATH_DEF(7),
    END_DEVICE_PATH_DEF
  },
};

#define PCI_ALLOCATION_ATTRIBUTES       EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM | \
                                        EFI_PCI_HOST_BRIDGE_MEM64_DECODE

GLOBAL_REMOVE_IF_UNREFERENCED
CHAR16 *mPciHostBridgeLibAcpiAddressSpaceTypeStr[] = {
  L"Mem", L"I/O", L"Bus"
};

STATIC PCI_ROOT_BRIDGE mRootBridge[PCI_HOST_MAX_COUNT] = {
  //Host Bridge 0
  {
    0,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x0
    }, {
      // Mem
      0x0,
      0x0,
      0x0
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x0
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[0]
  },
  //Host Bridge 1
  {
    1,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x100000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x100000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x100000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[1]
  },
  //Host Bridge 2
  {
    2,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x200000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x200000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x200000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[2]
  },
  //Host Bridge 3
  {
    3,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x300000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x300000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x300000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[3]
  },
  //Host Bridge 4
  {
    4,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x400000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x400000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x400000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[4]
  },
  //Host Bridge 5
  {
    5,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x500000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x500000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x500000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[5]
  },
  //Host Bridge 6
  {
    6,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x600000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x600000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x600000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[6]
  },
  //Host Bridge 1
  {
    7,                                              // Segment
    0,                                              // Supports
    0,                                              // Attributes
    TRUE,                                           // DmaAbove4G
    FALSE,                                          // NoExtendedConfigSpace
    FALSE,                                          // ResourceAssigned
    PCI_ALLOCATION_ATTRIBUTES,                      // AllocationAttributes
    {
      // Bus
      0x0,
      0x0
    }, {
      // Io
      0x0,
      0x0,
      0x700000000000
    }, {
      // Mem
      0x0,
      0x0,
      0x700000000000
    }, {
      // MemAbove4G
      0x0,
      0x0,
      0x700000000000
    }, {
      // PMem
      MAX_UINT64,
      0x0
    }, {
      // PMemAbove4G
      MAX_UINT64,
      0x0
    },
    (EFI_DEVICE_PATH_PROTOCOL *)&mEfiPciRootBridgeDevicePath[7]
  }
};

/**
  Return all the root bridge instances in an array.

  @param[out] Count  Return the count of root bridge instances.

  @return All the root bridge instances in an array.
          The array should be passed into PciHostBridgeFreeRootBridges()
          when it's not used.

**/
PCI_ROOT_BRIDGE *
EFIAPI
PciHostBridgeGetRootBridges (
  OUT UINTN     *Count
  )
{
  PHYTIUM_PCI_HOST_BRIDGE       *HostBridge;
  PHYTIUM_PCI_HOST_BLOCK        *PciHostBlock;
  UINT32                        Index;
  VOID                          *Buffer;
  UINTN                         Size;
  PSSI_STATUS                   PssiStatus;

  PssiStatus = PSSI_SUCCESS;
  *Count = 0;
  Size = 4 * EFI_PAGE_SIZE;
  Buffer = AllocatePages (4);
  if (Buffer == NULL) {
    DEBUG ((DEBUG_ERROR, "Allocate Pci Host Bridge Buffer Failed!\n"));
    return NULL;
  }
  PssiStatus = PssiGetPciHostBridgeInfo (
                 (PHYTIUM_PCI_HOST_BRIDGE *) Buffer,
                 &Size
                 );
  if (PSSI_ERROR(PssiStatus)) {
    DEBUG ((DEBUG_ERROR, "Get Pci Host Bridge Failed!\n"));
    return NULL;
  }

  HostBridge = (PHYTIUM_PCI_HOST_BRIDGE *) Buffer;
  if (HostBridge->PciHostCount > PCI_HOST_MAX_COUNT) {
    DEBUG ((DEBUG_ERROR, "Pci host count more than %d\n", PCI_HOST_MAX_COUNT));
  }

  *Count = HostBridge->PciHostCount;
  PciHostBlock = HostBridge->PciHostBlock;
  for (Index = 0; Index < HostBridge->PciHostCount; Index++) {
    DEBUG ((DEBUG_INFO,
            "HOST:%x, IoBase:%lx, IoSize:%x, Mem32Base:%lx, Mem32Size:%x, Mem64Base:%lx, Mem64Size:%lx\n",
            Index,
            PciHostBlock->IoBase,
            PciHostBlock->IoSize,
            PciHostBlock->Mem32Base,
            PciHostBlock->Mem32Size,
            PciHostBlock->Mem64Base,
            PciHostBlock->Mem64Size
            ));
    mRootBridge[Index].Bus.Base  = PciHostBlock->BusStart;
    mRootBridge[Index].Bus.Limit = PciHostBlock->BusEnd;
    mRootBridge[Index].Io.Base   = PciHostBlock->IoBase & 0xFFFFFFFF;
    mRootBridge[Index].Io.Limit  = mRootBridge[Index].Io.Base + PciHostBlock->IoSize - 1;
    mRootBridge[Index].Mem.Base  = PciHostBlock->Mem32Base & 0xFFFFFFFF;
    mRootBridge[Index].Mem.Limit = mRootBridge[Index].Mem.Base + PciHostBlock->Mem32Size - 1;
    mRootBridge[Index].MemAbove4G.Base  = PciHostBlock->Mem64Base & 0xFFFFFFFFFFF;
    mRootBridge[Index].MemAbove4G.Limit = mRootBridge[Index].MemAbove4G.Base + PciHostBlock->Mem64Size - 1;
    DEBUG ((DEBUG_INFO,
            "Root Bridge:%x, IoBase:%lx, IoSize:%x, Mem32Base:%lx, Mem32Size:%x, Mem64Base:%lx, Mem64Size:%lx\n",
            Index,
            mRootBridge[Index].Io.Base,
            mRootBridge[Index].Io.Limit,
            mRootBridge[Index].Mem.Base,
            mRootBridge[Index].Mem.Limit,
            mRootBridge[Index].MemAbove4G.Base,
            mRootBridge[Index].MemAbove4G.Limit
            ));
    PciHostBlock++;
  }

  if (Buffer != NULL) {
    FreePages (Buffer, 4);
  }

  DEBUG ((DEBUG_INFO, "Pci Host Bridge Count : %d\n", *Count));
  return mRootBridge;
}


/**
  Free the root bridge instances array returned from PciHostBridgeGetRootBridges().

  @param[in] Bridges The root bridge instances array.
  @param[in] Count   The count of the array.

**/
VOID
EFIAPI
PciHostBridgeFreeRootBridges (
  IN PCI_ROOT_BRIDGE *Bridges,
  IN UINTN           Count
  )
{
}


/**
  Inform the platform that the resource conflict happens.

  @param[in] HostBridgeHandle Handle of the Host Bridge.
  @param[in] Configuration    Pointer to PCI I/O and PCI memory resource
                              descriptors. The Configuration contains the resources
                              for all the root bridges. The resource for each root
                              bridge is terminated with END descriptor and an
                              additional END is appended indicating the end of the
                              entire resources. The resource descriptor field
                              values follow the description in
                              EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL
                              SubmitResources().

**/
VOID
EFIAPI
PciHostBridgeResourceConflict (
  IN EFI_HANDLE                        HostBridgeHandle,
  IN VOID                              *Configuration
  )
{
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor;
  BOOLEAN IsPrefetchable;

  DEBUG ((DEBUG_INFO, "PciHostBridge: Resource conflict happens!\n"));
  Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration;
  while (Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) {
    for (; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) {
      ASSERT (Descriptor->ResType <
              ARRAY_SIZE (mPciHostBridgeLibAcpiAddressSpaceTypeStr));
      DEBUG ((DEBUG_INFO, " %s: Length/Alignment = 0x%lx / 0x%lx\n",
              mPciHostBridgeLibAcpiAddressSpaceTypeStr[Descriptor->ResType],
              Descriptor->AddrLen,
              Descriptor->AddrRangeMax
              ));
      if (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) {

        IsPrefetchable = (Descriptor->SpecificFlag &
          EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) != 0;

        DEBUG ((DEBUG_INFO, "     Granularity/SpecificFlag = %ld / %02x%s\n",
          Descriptor->AddrSpaceGranularity,
          Descriptor->SpecificFlag,
          (IsPrefetchable) ? L" (Prefetchable)" : L""
          ));
      }
    }
    //
    // Skip the end descriptor for root bridge
    //
    ASSERT (Descriptor->Desc == ACPI_END_TAG_DESCRIPTOR);
    Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) (
                   (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor + 1
                   );
  }
}
